import React, { useEffect, useState } from 'react';
import cn from 'classnames';
import { productInfo, uploadProductLicense } from '~/API/index';
import s from './style.module.css';
import i from '@/index.module.css';
import BreadCrumb from '@/components/BreadCrumb';
import { Loading, Upload, Dialog, Button, Progress, Message } from '@knownsec/react-component';
import { getErrorMessage } from '@/common/constant';
import { MODULES,SECURITY_MODULES } from '@/common/common.js';
import moment from 'moment';
export default function ProductInfo() {
  const text=JSON.parse(localStorage.oem)
  const [loading, setLoading] = useState(true);
  const [yet, setYet] = useState(0);
  const [roleList, setRoleList] = useState([]);
  const [upVisible, setUpVisible] = useState(false);
  const [percent, setPercent] = useState(0);
  const [modules,setModules] = useState('')
  const [product, setProduct] = useState({
    company_name: '--',
    custom_content:{},
    product_name: '--',
    is_trial: '--',
    product_status: '--',
    device_id: '--',
    product_type: '--',
    version: '--',
    expiry_time: '',
    customer: ''
  });
  useEffect(() => {
    getInfo();
  }, []);
  const changeVisible = () => {
    setUpVisible(false);
  };
  const getInfo = () => {
    setLoading(true);
    const checkedMod = (boolean, modules) => {
      return Object.entries(MODULES)
        .filter(([fk, fv]) => {
          const _in = modules.includes(fk);
          return boolean ? _in : !_in;
        })
        .map(([mk, mv]) => {
          if (mk === 'securityEvent') {
            const secStr = Object.entries(SECURITY_MODULES)
              .filter(([k, v]) => {
                const _in = modules.includes(k);
                return _in;
              })
              .map(([k, v]) => {
                return v;
              })
              .join('、');
              mv += `(${secStr})`;
          }
          return mv;
        })
        .join(' | ');
    };
    productInfo('GET')
      .then((res) => {
        const _modules=checkedMod(true,res.data.modules)
        setYet(1);
        setLoading(false);
        setProduct(res.data);
        setRoleList(res.user_group || []);
        setModules(_modules||'--')
      })
      .catch(() => setLoading(false));
  };
  const uploadFile = ({ file }) => {
    setPercent(0);
    setUpVisible(true);
    let timer = null;
    let per = 0;
    timer = setInterval(() => {
      if (per > 87) {
        clearInterval(timer);
      } else {
        const d = Math.ceil(Math.random() * 10);
        per += d;
        setPercent((x) => (x += d));
      }
    }, 300);
    const formData = new FormData();
    formData.append('file', file);
    uploadProductLicense('POST', formData, true)
      .then((res) => {
        clearInterval(timer);
        setPercent(100);
        setUpVisible(false);
        Message.show({
          type: res.status,
          message: res.message,
        });
        getInfo();
      })
      .catch((err) => {
        Message.show({ type: 'error', message: getErrorMessage(err, 'data') });
        setPercent(0);
        setUpVisible(false);
      }).finally(async () => {
        // 不管成功失败都更新localStorage.info
        const Info = await productInfo(); 
        if (Info.status == 'success') {
          Info.data.modules.push('change_check');
          Info.data.change_check = { crawler_depth: 10, crawler_max_page: 100000, seconds: 1800 };
          localStorage.info = JSON.stringify(Info.data);
        }
      });
  };
  return (
    <div className={i.mainContent}>
      <BreadCrumb arr={[{ link: '', name: '系统信息', active: true }]} />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <div className={s.bgc}>
          <div className={cn(i.pt24, i.pl20, i.pr20, i.pb20, i.pr)}>
            <Loading show={loading} />
            <p className={s.wordMain_h} style={{ display: product.product_status !== '有效' ? 'block' : 'none' }}>
            {`当前证书已到期，请${localStorage.group === '管理员'?'':'联系管理员'}重新上传证书`}
            </p>
            <div>
              <span className={s.key}>公司名称：</span>
              <span className={s.ml40}>{product.company_name}</span>
            </div>
            {product.custom_content?.company_name && <div className={i.mt20}>
              <span className={s.key}>客户名称：</span>
              <span className={s.ml40}>{product.custom_content.company_name}</span>
            </div>}
            <div className={i.mt20}>
              <span className={s.key}>产品名称：</span>
              <span className={s.ml40}>{product.product_name}</span>
            </div>
            <div className={i.mt20}>
              <span className={s.key}>产品型号：</span>
              <span className={s.ml40}>{product.product_type}</span>
            </div>
            {product.is_trial&&<div className={i.mt20}>
              <span className={s.key}>版本状态：</span>
              <span className={s.ml40}>
              试用版
              </span>
            </div>}
            <div className={i.mt20}>
              <span className={s.key}>设备标识：</span>
              <span className={s.ml40}>{product.device_id}</span>
            </div>
            {/* <div className={i.mt20}>
              <span className={s.key}>证书编号</span>
              <span className={s.ml40}>{'--'}</span>
            </div>
            <div className={i.mt20}>
              <span className={s.key}>授权期限</span>
              <span className={s.ml40}>{'--'}</span>
            </div> */}
            <div className={i.mt20}>
              <span className={s.key}>系统版本：</span>
              <span className={s.ml40}>{product.system_version? product.system_version:product.version?product.version:'--'}</span>
            </div>
            <div className={i.mt20}>
              <span className={s.key}>插件版本：</span>
              <span className={s.ml40}>{product.data_version || '--'}</span>
            </div>
            {product.customer&&<div className={i.mt20}>
              <span className={s.key}>授权单位：</span>
              <span className={s.ml40}>{product.customer}</span>
            </div>}
            <div className={i.mt20}>
              <span className={s.key}>用户上限：</span>
              <span className={s.ml40}>{product.max_user_number || '--'}</span>
            </div>
            <div className={i.mt20}>
              <span className={s.key}>业务系统上限：</span>
              <span className={s.ml40}>{product.max_target_number || '--'}</span>
            </div>
            {product.is_trial&&<div className={i.mt20}>
              <span className={s.key}>扫描次数上限：</span>
              <span className={s.ml40}>{product.max_task_session_number || '--'}</span>
            </div>}
            <div className={i.mt20}>
              <span className={s.key}>证书状态：</span>
              <span className={s.ml40}>{product.product_status}</span>
              <span>&nbsp;({moment(product.expiry_time).format('YYYY-MM-DD HH:mm:ss')})</span>
            </div>
            <div className={i.mt20}>
              <span className={s.key}>授权模块：</span>
              <span className={s.ml40}>
              {modules}
              </span>
            </div>
            {roleList.indexOf('管理员') > -1 ? (
              <div className={cn(i.mt20, i.df, i.aic)}>
                <span className={s.key}>导入证书：</span>
                <Upload className={s.ml40} customRequest={uploadFile} showUploadList={false}>
                  <Button type="primary">点击上传产品证书文件</Button>
                </Upload>
              </div>
            ) : null}

            <div className={cn(i.mt20)}>
              <div className={cn(s.key, i.dib, i.vat)}>版权声明：</div>
              <div className={cn(i.dib, s.con, i.vat)}>
                {yet
                  ? `版权所有©许可证颁发者${text.home}，保留所有权利（公司徽标、产品徽标、公司名称、产品名称），在中国或其他国家（地区）的商标或注册商标，其商标是其各自所有者财产。产品所用到的第三方组件所有权为第三方所有。`
                  : '--'}
              </div>
            </div>
          </div>
        </div>
        <Dialog
          className={cn(i.w400)}
          title="上传进度"
          visible={upVisible}
          cancelText=""
          confirmText=""
          onhide={changeVisible}
        >
          <div className={i.p20}>
            <p className={cn(i.tac)}>进度:{percent}%</p>
            <Progress percent={percent + '%'} className={i.mt10} />
          </div>
        </Dialog>
      </div>
    </div>
  );
}
